<?php

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');

/* 载入语言文件 */
require_once(ROOT_PATH . 'languages/' .$_CFG['lang']. '/user.php');
require_once(ROOT_PATH . 'languages/' .$_CFG['lang']. '/projects.php');

$user_id = isset($_REQUEST['user_id']) ? intval($_REQUEST['user_id']) : $_SESSION['user_id'];
$action  = isset($_REQUEST['act']) ? trim($_REQUEST['act']) : 'default';

// 不需要登录的操作或自己验证是否登录（如ajax处理）的act
$not_login_arr =
array('login','act_login','register','act_register','act_edit_password','get_password','send_pwd_email','password', 'logout', 'email_list', 'validate_email', 'send_hash_mail', 'is_registered', 'check_email','qpassword_name', 'get_passwd_question', 'check_answer');

/* 显示页面的action列表 */
$ui_arr = array('register', 'login', 'profile',
'message_list', 'get_password', 'reset_password', 'default','validate_email','aboutme','photo');

/*不登陆不可访问的界面*/
$ui_login = array('profile','aboutme','photo');

/* 如果是显示页面，对页面进行相应赋值 */
if (in_array($action, $ui_login))
{

    if(!$_SESSION['user_id'])
	{
		show_message('You need to log in before manage account', array($_LANG['back_up_page'], $_LANG['profile_lnk']), 'user.php?act=login', 'info');
	}
}

/* 如果是显示页面，对页面进行相应赋值 */
if (in_array($action, $ui_arr))
{
    assign_template();
    $smarty->assign('page_title', 'Login'); // 页面标题
    include_once(ROOT_PATH .'includes/lib_clips.php');
    $smarty->assign('data_dir',   DATA_DIR);   // 数据目录
	$smarty->assign('info',       get_user($user_id));
    $smarty->assign('action',     $action);
    $smarty->assign('lang',       $_LANG);
}



//用户中心欢迎页
if ($action == 'default')
{
    include_once(ROOT_PATH .'includes/lib_clips.php');
	$info = get_user($user_id);
    
    $smarty->assign('user_notice', $_CFG['user_notice']);
	
	if($user_id != $_SESSION['user_id'])
	{
		$smarty->assign('exerciser_watch', 1);
	}
	else
	{
		$smarty->assign('exerciser_watch', 0);
	}
	
	$sql = "SELECT user_type "." FROM " . $GLOBALS['ecs']->table('users')." WHERE user_id = '".$user_id."' ";
	$user_type= $db->getRow($sql);
	
	if($user_type['user_type'] == 1)
	{
		$sql = "SELECT * "." FROM " . $GLOBALS['ecs']->table('proposals')." AS pp JOIN " . $GLOBALS['ecs']->table('projects')." AS p "." WHERE pp.uid = '".$user_id."' AND pp.pid = p.pid ORDER by proposaledDate DESC LIMIT 3 ";
		$proposals = $db->getAll($sql);
		$smarty->assign('proposalsNum', count($proposals));
		$smarty->assign('proposals', $proposals);
	}
	else
	{
		$sql = "SELECT * "." FROM " . $GLOBALS['ecs']->table('projects')." WHERE uid = '".$user_id."' ORDER by createdDate DESC LIMIT 3 ";
		$projects= $db->getAll($sql);
		$smarty->assign('projectsNum',count($projects));
		$smarty->assign('projects', $projects);
	}
	
		
	$sql = "SELECT * "." FROM " . $GLOBALS['ecs']->table('review')." AS r JOIN ". $GLOBALS['ecs']->table('users')." AS u "." WHERE r.reviewed_id = '".$user_id."' AND r.reviewer_id=u.user_id ";
	$reviewed = $db->getAll($sql);
	
	$info['rank_points'] = 0;
	$reviewed_count = count($reviewed);
	foreach( $reviewed as $rev)
	{		
		$info['rank_points'] = $info['rank_points'] + $rev['rank_score'];
	}
	
	
	if($reviewed_count != 0)
	{
		$info['rank_points'] = intval($info['rank_points']/$reviewed_count);
	}
	else
	{
		$info['rank_points'] = 0;
	}
	
	$page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1;
	$pagesize = 0;
	$pager = get_pager('user.php', array('act' => 'default'), $reviewed_count, $page, $pagesize);
	$reviewed_lists = get_reviewed_list($pagesize, $pager['start'], $user_id);
		
	$sql = "SELECT * "." FROM " . $GLOBALS['ecs']->table('review')." AS r JOIN ". $GLOBALS['ecs']->table('users')." AS u "." WHERE r.reviewer_id = '".$user_id."' AND r.reviewed_id=u.user_id ";
	$reviewer = $db->getAll($sql);	
	
	$reviewer_count = count($reviewer);
	$page_2 = isset($_REQUEST['page_2']) ? intval($_REQUEST['page_2']) : 1;
	$pagesize = 0;
	$pager_2 = get_pager('user.php', array('act' => 'default'), $reviewer_count, $page_2, $pagesize);
	$reviewer_lists = get_reviewer_list($pagesize, $pager_2['start'], $user_id);
	
	$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('projects')." AS p JOIN ".$GLOBALS['ecs']->table('proposals')." AS pp ". " WHERE p.uid = '$user_id' AND pp.pid=p.pid AND awarded=0 AND accepted=0 AND watched=0 ";
	$alerts = $GLOBALS['db']->getAll($sql);
	$smarty->assign('alerts', $alerts);

	$smarty->assign('pager', $pager);
	$smarty->assign('pager', $pager_2);
	$smarty->assign('reviewed', $reviewed_lists);
	$smarty->assign('reviewed_count', $reviewed_count);
	$smarty->assign('reviewer', $reviewer_lists);
	$smarty->assign('reviewer_count', $reviewer_count);
	$tab = isset($_REQUEST['tab'])?intval($_REQUEST['tab']):1;
	$smarty->assign('tab', $tab);
	$smarty->assign('info', $info);			
    $smarty->display('user_clips.dwt');
}

/* 显示会员注册界面 */
if ($action == 'register')
{
    if (!isset($back_act) && isset($GLOBALS['_SERVER']['HTTP_REFERER']))
    {
        $back_act = strpos($GLOBALS['_SERVER']['HTTP_REFERER'], 'user.php') ? './index.php' : $GLOBALS['_SERVER']['HTTP_REFERER'];
    }
     $smarty->assign('type',$_GET['type']);
    $smarty->display('user_passport.dwt');
}

/* 注册会员的处理 */
elseif ($action == 'act_register')
{
    
        include_once(ROOT_PATH . 'includes/lib_passport.php');

        $username = isset($_POST['username']) ? trim($_POST['username']) : '';
        $password = isset($_POST['password']) ? trim($_POST['password']) : '';
        $email    = isset($_POST['email']) ? trim($_POST['email']) : '';
        $user_type    = isset($_POST['user_type']) ? trim($_POST['user_type']) : '';
        $back_act = isset($_POST['back_act']) ? trim($_POST['back_act']) : '';

        if (strlen($password) < 6)
        {
            show_message($_LANG['passport_js']['password_shorter']);
        }

        if (strpos($password, ' ') > 0)
        {
            show_message($_LANG['passwd_balnk']);
        }

        if (register($username, $password, $email, $user_type) !== false)
        {
            show_message(sprintf($_LANG['register_success'], $username), array($_LANG['back_up_page'], $_LANG['profile_lnk']), 'user.php?act=aboutme', 'info');
        }
        else
        {
            $err->show($_LANG['sign_up'], 'user.php?act=register');
        }

}

/* 验证用户注册邮件 */
elseif ($action == 'validate_email')
{
    $hash = empty($_GET['hash']) ? '' : trim($_GET['hash']);
    if ($hash)
    {
        include_once(ROOT_PATH . 'includes/lib_passport.php');
        $id = register_hash('decode', $hash);
        if ($id > 0)
        {
            $sql = "UPDATE " . $ecs->table('users') . " SET is_validated = 1 WHERE user_id='$id'";
            $db->query($sql);
            $sql = 'SELECT user_name, email FROM ' . $ecs->table('users') . " WHERE user_id = '$id'";
            $row = $db->getRow($sql);
            show_message(sprintf($_LANG['validate_ok'], $row['user_name'], $row['email']),$_LANG['profile_lnk'], 'user.php');
        }
    }
    show_message($_LANG['validate_fail']);
}

/* 验证用户注册用户名是否可以注册 */
elseif ($action == 'is_registered')
{
    include_once(ROOT_PATH . 'includes/lib_passport.php');

    $username = trim($_GET['username']);
    $username = json_str_iconv($username);

    if ($user->check_user($username) || admin_registered($username))
    {
        echo 'true';
    }
    else
    {
        echo 'true';
    }
}

/* 验证用户邮箱地址是否被注册 */
elseif($action == 'check_email')
{
    $email = trim($_GET['email']);
    if ($user->check_email($email))
    {
        echo 'false';
    }
    else
    {
        echo 'ok';
    }
}
/* 用户登录界面 */
elseif ($action == 'login')
{
    if (empty($back_act))
    {
        if (empty($back_act) && isset($GLOBALS['_SERVER']['HTTP_REFERER']))
        {
            $back_act = strpos($GLOBALS['_SERVER']['HTTP_REFERER'], 'user.php') ? './index.php' : $GLOBALS['_SERVER']['HTTP_REFERER'];
        }
        else
        {
            $back_act = 'user.php';
        }

    }
	
    $smarty->assign('back_act', $back_act);
    $smarty->display('user_passport.dwt');
}

/* 处理会员的登录 */
elseif ($action == 'act_login')
{
    $username = isset($_POST['email']) ? trim($_POST['email']) : '';
    $password = isset($_POST['password']) ? trim($_POST['password']) : '';
    $back_act = $GLOBALS['_SERVER']['HTTP_REFERER'];

    if ($user->login($username, $password,isset($_POST['remember'])))
    {
        update_user_info();
		
		//判断数据库中的数据，对于已经award但是没有accept的project，判断accept时间期限，如果超过accept时间（awardDate），则清楚该proposal的award,将该project的status置为1，可继续投标、定标
		$fctime= date("Y-m-d H:i:s ",time());
		$sql = "SELECT * "." FROM " . $GLOBALS['ecs']->table('proposals'). " WHERE awarded=1 AND accepted=0 AND awardDate<'$fctime' ";
		$not_accept_ontime= $db->getALL($sql);
											
		foreach($not_accept_ontime as $each)
		{			
			$sql = "UPDATE " . $ecs->table('proposals') . " SET awarded=0 "." WHERE ppid='".$each[ppid]."'";
			$db->query($sql);
			
			$sql = "SELECT * FROM " . $ecs->table('projects') . " AS p JOIN ". $ecs->table('proposals') . " AS pp " . " WHERE pp.ppid='".$each[ppid]."' ";
			$tmp = $db->getRow($sql);
												
			$createdDate = strtotime($tmp['awardDate']);
						
			if($tmp['quoting'] == 1)
			{
				$tmpDate = $createdDate + 24*60*60*14;
				$endDate = date("Y-m-d H:i:s", $tmpDate); 				
			}
			else
			{
				$endDate = date("Y-m-d H:i:s", $createdDate + 24*60*60*30);
			}
			$createdDate = date("Y-m-d H:i:s", $createdDate);
					
			$sql = "UPDATE " . $ecs->table('projects') . " SET status=1, createdDate='$createdDate', endDate='$endDate' "." WHERE pid='".$each[pid]."'";
			$db->query($sql);
		}
		
        show_message($_LANG['login_success'] , array($_LANG['back_up_page'], $_LANG['profile_lnk']), 'user.php', 'info');
    }
    else
    {
        $_SESSION['login_fail'] ++ ;
        show_message($_LANG['login_failure'], $_LANG['relogin_lnk'], $back_act, 'error');
    }
}

/* 退出会员中心 */
elseif ($action == 'logout')
{
    if (!isset($back_act) && isset($GLOBALS['_SERVER']['HTTP_REFERER']))
    {
        $back_act = strpos($GLOBALS['_SERVER']['HTTP_REFERER'], 'user.php') ? './index.php' : $GLOBALS['_SERVER']['HTTP_REFERER'];
    }

    $user->logout();
    $ucdata = empty($user->ucdata)? "" : $user->ucdata;
    show_message($_LANG['logout'] . $ucdata, '', 'index.php', 'info');
}

/* 个人资料页面 */
elseif ($action == 'profile')
{
    include_once(ROOT_PATH . 'includes/lib_transaction.php');

    $user_info = get_profile($user_id);
    $smarty->assign('profile', $user_info);
    $smarty->display('user_transaction.dwt');
}

/**/
elseif ($action == 'aboutme')
{
	include_once(ROOT_PATH . 'includes/lib_clips.php');

	$user_info = get_user($user_id);
	$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('gender');
	$gender=$db->getAll($sql);
	
	if($user_info['user_type'] == 1)
	{
		/* Get Options */
		$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('experience');
		$experience=$db->getAll($sql);
	
		$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('trainingservice');
		$trainingservice=$db->getAll($sql);
	
		$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('gender');
		$gender=$db->getAll($sql);
	
		$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('edulevel');
		$edulevel=$db->getAll($sql);
		
		$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('credentials');
		$credentials=$db->getAll($sql);
		
		$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('specialties_tags'). " ORDER by tag_num DESC LIMIT 20";
		$most_specialties=$db->getAll($sql);
	
    	$smarty->assign('experience', $experience);
		$smarty->assign('trainingservice', $trainingservice);
		$smarty->assign('gender', $gender);
		$smarty->assign('edulevel', $edulevel);
		$smarty->assign('credentials', $credentials);
		$smarty->assign('most_specialties', $most_specialties);
	}
	if($user_id != $_SESSION['user_id'])
	{
		$smarty->assign('display_button', 0);
	}
	else
	{
		$smarty->assign('display_button', 1);
	}
	
	$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('city');
	$citys=$db->getAll($sql);
	$tmp = '';
	foreach($citys as $city)
	{
		$tmp = $tmp.$city['city_name'].',';
	}
	$smarty->assign('citys', $tmp);
	
	$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('state');
	$states=$db->getAll($sql);
	$tmp = '';
	foreach($states as $state)
	{
		$tmp = $tmp.$state['state_name'].',';
	}
	$smarty->assign('states', $tmp);
	
	$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('country');
	$countrys=$db->getAll($sql);
	$tmp = '';
	foreach($countrys as $country)
	{
		$tmp = $tmp.$country['country_name'].',';
	}
	$smarty->assign('countrys', $tmp);
	
	$smarty->assign('gender', $gender);
    $smarty->assign('profile', $user_info);
    $smarty->display('user_aboutme.dwt');
}

/**/
elseif ($action == 'photo')
{
	include_once(ROOT_PATH . 'includes/lib_transaction.php');

    $user_info = get_profile($user_id);
	$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('gender');
	$gender=$db->getAll($sql);
	
	$smarty->assign('gender', $gender);
    $smarty->assign('profile', $user_info);
    $smarty->display('user_photo.dwt');
}

/* 修改个人资料的处理 */
elseif ($action == 'act_edit_profile')
{
    include_once(ROOT_PATH . 'includes/lib_transaction.php');

    $birthday = trim($_POST['birthdayYear']) .'-'. trim($_POST['birthdayMonth']) .'-'.
    trim($_POST['birthdayDay']);
    $email = trim($_POST['email']);
    $other['msn'] = $msn = isset($_POST['extend_field1']) ? trim($_POST['extend_field1']) : '';
    $other['qq'] = $qq = isset($_POST['extend_field2']) ? trim($_POST['extend_field2']) : '';
    $other['office_phone'] = $office_phone = isset($_POST['extend_field3']) ? trim($_POST['extend_field3']) : '';
    $other['home_phone'] = $home_phone = isset($_POST['extend_field4']) ? trim($_POST['extend_field4']) : '';
    $other['mobile_phone'] = $mobile_phone = isset($_POST['extend_field5']) ? trim($_POST['extend_field5']) : '';
    $sel_question = empty($_POST['sel_question']) ? '' : $_POST['sel_question'];
    $passwd_answer = isset($_POST['passwd_answer']) ? trim($_POST['passwd_answer']) : '';
	
    if (!empty($office_phone) && !preg_match( '/^[\d|\_|\-|\s]+$/', $office_phone ) )
    {
        show_message($_LANG['passport_js']['office_phone_invalid']);
    }
    if (!empty($home_phone) && !preg_match( '/^[\d|\_|\-|\s]+$/', $home_phone) )
    {
         show_message($_LANG['passport_js']['home_phone_invalid']);
    }
    if (!is_email($email))
    {
        show_message($_LANG['msg_email_format']);
    }
    if (!empty($msn) && !is_email($msn))
    {
         show_message($_LANG['passport_js']['msn_invalid']);
    }
    if (!empty($qq) && !preg_match('/^\d+$/', $qq))
    {
         show_message($_LANG['passport_js']['qq_invalid']);
    }
    if (!empty($mobile_phone) && !preg_match('/^[\d-\s]+$/', $mobile_phone))
    {
        show_message($_LANG['passport_js']['mobile_phone_invalid']);
    }


    $profile  = array(
        'user_id'  => $user_id,
        'email'    => isset($_POST['email']) ? trim($_POST['email']) : '',
        'sex'      => isset($_POST['sex'])   ? intval($_POST['sex']) : 0,
        'birthday' => $birthday,
        'other'    => isset($other) ? $other : array()
        );


    if (edit_profile($profile))
    {
        show_message($_LANG['edit_profile_success'], $_LANG['profile_lnk'], 'user.php?act=profile', 'info');
    }
    else
    {
        if ($user->error == ERR_EMAIL_EXISTS)
        {
            $msg = sprintf($_LANG['email_exist'], $profile['email']);
        }
        else
        {
            $msg = $_LANG['edit_profile_failed'];
        }
        show_message($msg, '', '', 'info');
    }
}

/* 修改个人资料的处理 */
elseif ($action == 'act_aboutme')
{
    include_once(ROOT_PATH . 'includes/lib_clips.php');
	$user_info = get_user($user_id);
	
	if($user_info['user_type'] == 1)
	{			
		$other['training_service'] = $training_service = isset($_POST['training_service']) ? intval($_POST['training_service']) : 0;
    	$other['experience'] = $experience = isset($_POST['experience']) ? intval($_POST['experience']) : 0;
    	$other['training_specialties'] = $training_specialties = isset($_POST['training_specialties_value']) ? trim($_POST['training_specialties_value']) : '';
		
    	$other['credentials'] = $credentials = isset($_POST['credentials_choose']) ? trim($_POST['credentials_choose']) : '';
    	$other['firstname'] = $firstname = isset($_POST['firstname']) ? trim($_POST['firstname']) : '';
    	$other['lastname'] = $lastname = isset($_POST['lastname']) ? trim($_POST['lastname']) : '';
    	$other['sex'] = $gender = isset($_POST['gender']) ? intval($_POST['gender']) : 0;
		$other['business_name'] = $gender = isset($_POST['business_name']) ? trim($_POST['business_name']) : '';
		$other['education'] = $education = isset($_POST['education']) ? intval($_POST['education']) : 0;
    	$other['school'] = $school = isset($_POST['school']) ? trim($_POST['school']) : '';
		$other['major'] = $major = isset($_POST['major']) ? trim($_POST['major']) : '';
		$other['BIO'] = $BIO = isset($_POST['BIO']) ? trim($_POST['BIO']) : '';
    	$other['zipcode'] = $zipcode = isset($_POST['zipcode']) ? trim($_POST['zipcode']) : '';
    	$other['address'] = $city = isset($_POST['city']) ? trim($_POST['city']) : '';
		$other['province'] = $province = isset($_POST['province']) ? trim($_POST['province']) : '';
		$other['country'] = $country = isset($_POST['country']) ? trim($_POST['country']) : '';
   			
		if (!empty($zipcode) && !preg_match('/^\d+$/', $zipcode))
    	{
         	show_message($_LANG['zipcode_invalid']);
    	}
		
    	if ($GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('users'), $other, 'UPDATE', "user_id = '$_SESSION[user_id]'"))
    	{
			$specialties = explode(',',$training_specialties);
			for($i = 0; $i < count($specialties) - 1; $i++)
			{
				$sql = "SELECT tag_num FROM ".$ecs->table('specialties_tags')."  WHERE tag_name='".$specialties[$i]."'";
				$number = $db->getOne($sql);
				if($number != '')
				{
					$number = $number + 1;
					$sql = "UPDATE ".$ecs->table('specialties_tags')." SET tag_num='".$number."'  WHERE tag_name='".$specialties[$i]."'";
					$db->query($sql);
				}
				else
				{
					$sql = "INSERT ".$ecs->table('specialties_tags')."(tag_name, tag_num) VALUES('".$specialties[$i]."', 1 ) ";
					$db->query($sql);
				}
			}
			
        	if($save == 'Save')
        		show_message($_LANG['edit_profile_success'], $_LANG['profile_lnk'], 'user.php?act=aboutme', 'info');
			else
				show_message($_LANG['edit_profile_success'], $_LANG['profile_lnk'], 'user.php?act=photo', 'info');
    	}
    	else
    	{
        	if ($user->error == ERR_EMAIL_EXISTS)
        	{
            	$msg = sprintf($_LANG['email_exist'], $profile['email']);
        	}
        	else
        	{
            	$msg = $_LANG['edit_profile_failed'];
        	}
        	show_message($msg, '', '', 'info');
    	}
  	}
	else
	{
		$other['firstname'] = $firstname = isset($_POST['firstname']) ? trim($_POST['firstname']) : '';
    	$other['lastname'] = $lastname = isset($_POST['lastname']) ? trim($_POST['lastname']) : '';
    	$other['sex'] = $gender = isset($_POST['gender']) ? intval($_POST['gender']) : '';
    	$other['zipcode'] = $zipCode = isset($_POST['zipcode']) ? trim($_POST['zipcode']) : '';
    	$other['address'] = $city = isset($_POST['city']) ? trim($_POST['city']) : '';
		$other['province'] = $city = isset($_POST['province']) ? trim($_POST['province']) : '';
		$other['country'] = $city = isset($_POST['country']) ? trim($_POST['country']) : '';
		$other['BIO'] = $BIO = isset($_POST['BIO']) ? trim($_POST['BIO']) : '';
		$save = $_POST['save'];
		
    	if (!empty($zipcode) && !preg_match('/^\d+$/', $zipcode))
    	{
         	show_message($_LANG['zipcode_invalid']);
    	}
		
    	if ($GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('users'), $other, 'UPDATE', "user_id = '$_SESSION[user_id]'"))
    	{
			if($save == 'Save')
        	show_message($_LANG['edit_profile_success'], $_LANG['profile_lnk'], 'user.php?act=aboutme', 'info');
			else
			show_message($_LANG['edit_profile_success'], $_LANG['profile_lnk'], 'user.php?act=photo', 'info');
    	}
		
    	else
    	{
        	if ($user->error == ERR_EMAIL_EXISTS)
        	{
            	$msg = sprintf($_LANG['email_exist'], $profile['email']);
        	}
        	else
        	{
            	$msg = $_LANG['edit_profile_failed'];
        	}
        	show_message($msg, '', 'user.php?act=photo', 'info');
    	}
	}
    
}

/* 修改个人资料的处理 */
elseif ($action == 'act_photo')
{
	
	// This is the temporary file created by PHP     	
	/* Save The Accessories */
	if($_FILES['userfile']['error']>0)
	{
		switch($_FILES['userfile']['error'])
		{
			case 1:	$msg='File exceeded upload_max_filesize';break;
			case 2:	$msg='File exceeded max_file_size';break;
			case 3: $msg='File only partially uploaded';break;
			case 4: $msg='No file uploaded';break;
		}
		show_message($msg, $_LANG['back_up_page'], 'user.php?act=photo', 'info');	
	}
		
	$sql = "SELECT photo FROM " . $ecs->table('users') . " WHERE user_id='".$_SESSION[user_id]."'";
	$photo = $db->getOne($sql);
	if($photo != '')
	unlink($photo);
	
	$str = '';
    for($i = 0; $i < 9; $i++)
    {
        $str .= mt_rand(0, 9);
    }
    $str = gmtime() . $str;
	
	$filename = $_FILES['userfile']['name'];
	$filename = str_replace("#","",$filename);
	
	$upfile = './images/'.$str.'_'.$filename;
	
	
	
	if(is_uploaded_file($_FILES['userfile']['tmp_name']))
	{
		if(!move_uploaded_file($_FILES['userfile']['tmp_name'],$upfile))
		{
			$msg = 'Problem: Could not move file to destination directory';
			show_message($msg, $_LANG['back_up_page'], 'user.php?act=photo', 'info');	
		}
	}
	else
	{
		$msg = 'Problem: Possible file upload attack. Filename:'.$_FILES['userfile']['name'];
		show_message($msg, $_LANG['back_up_page'], 'user.php?act=photo', 'info');	
	}
	
	
    $tmp_name=$_FILES['userfile']['tmp_name']; 
 	$imginfo=getimagesize($upfile); 
	// Create an Image from it so we can do the resize
	switch( $imginfo[2])
	{
		case 1:
			$src = imagecreatefromgif($upfile);
			break;
		case 2:
			$src = imagecreatefromjpeg($upfile);
			break;
		case 3:
			$src = imagecreatefrompng($upfile);
			break;
		default:
			show_message("Not image file, please try again", $_LANG['back_up_page'], 'user.php?act=photo', 'info');
			break;
	}
    

	   
    // Create an Image from it so we can do the resize 
	/*
	if($_FILES['userfile']["type"] == "image/jpeg")
	{    
		$src = imagecreatefromjpeg($upfile);
	}
	elseif($_FILES['userfile']['type'] == "image/gif")
	{
		$src = imagecreatefromgif($upfile);
	}
	*/
      
    // Capture the original size of the uploaded image   
	list($width,$height)=getimagesize($upfile);   
      
    // For our purposes, I have resized the image to be  
    // 600 pixels wide, and maintain the original aspect  
    // ratio. This prevents the image from being "stretched"  
    // or "squashed". If you prefer some max width other than  
    // 600, simply change the $newwidth variable  
    $newwidth=200;  
    $newheight=($height/$width)*$newwidth; 
	#$newheight=250; 
    $tmp=imagecreatetruecolor($newwidth,$newheight);  
      
    // this line actually does the image resizing, copying from the original  
    // image into the $tmp image  
    imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);   
      
    // now write the resized image to disk. I have assumed that you want the  
    // resized, uploaded image file to reside in the ./images subdirectory.  
    // $des_filename = "./images/head_picture/".$_SESSION[user_id]."_".$str.'_'. $_FILES['userfile']['name'];
	$des_filename = "./images/head_picture/".$_SESSION[user_id]."_".$str.'_'. $filename;  
    //imagejpeg($tmp,$des_filename,100);  
	
	switch( $imginfo[2])
	{
		case 1:
			imagegif($tmp,$des_filename,100);
			break;
		case 2:
			imagejpeg($tmp,$des_filename,100);
			break;
		case 3:
			imagepng($tmp,$des_filename);
			break;
		default:
			break;
	}
     	  
    imagedestroy($src);  
    imagedestroy($tmp); // NOTE: PHP will clean up the temp file it created when the request  
    // has completed.  
	unlink($upfile);
	$save = $_POST['save'];
		
	$sql = "UPDATE " . $ecs->table('users') . " SET photo='$des_filename' "." WHERE user_id='".$_SESSION[user_id]."'";
	if($db->query($sql) != false)
	{
		if($save == 'Save')
		show_message("Photo uploaded!", $_LANG['back_up_page'], 'user.php?act=photo', 'info');	
		else
		show_message("Photo uploaded!", $_LANG['back_up_page'], 'user.php', 'info');	
	}
	else
	{
		show_message("Upload Photo Failed, Please Try Again!", $_LANG['back_up_page'], 'user.php?act=photo', 'info');
	} 
}

/* 修改个人资料的处理 */
elseif ($action == 'delete_photo')
{	
	$sql = "SELECT photo FROM " . $ecs->table('users') . " WHERE user_id='".$_SESSION[user_id]."'";
	$photo = $db->getOne($sql);
	if($photo != '')
	unlink($photo);
	
	$sql = "UPDATE " . $ecs->table('users') . " SET photo='' "." WHERE user_id='".$_SESSION[user_id]."'";
	if($db->query($sql) != false)
	{		
		show_message("Photo deleted!", $_LANG['back_up_page'], 'user.php?act=photo', 'info');	
	}
	else
	{
		show_message("Upload Photo Failed, Please Try Again!", $_LANG['back_up_page'], 'user.php', 'info');
	} 
}

/* 密码找回-->修改密码界面 */
elseif ($action == 'get_password')
{
    include_once(ROOT_PATH . 'includes/lib_passport.php');
	
    if (isset($_GET['code']) && isset($_GET['uid'])) //从邮件处获得的act
    {
        $code = trim($_GET['code']);
        $uid  = intval($_GET['uid']);

        /* 判断链接的合法性 */
        $user_info = $user->get_profile_by_id($uid);
        if (empty($user_info) || ($user_info && md5($user_info['user_id'] . $_CFG['hash_code'] . $user_info['reg_time']) != $code))
        {
            show_message($_LANG['parm_error'], $_LANG['back_home_lnk'], './', 'info');
        }

        $smarty->assign('uid',    $uid);
        $smarty->assign('code',   $code);
        $smarty->assign('action', 'reset_password');
		$smarty->assign('email',  $user_info['email']);
        $smarty->display('user_passport.dwt');
    }
    else
    {
        //显示用户名和email表单
        $smarty->display('user_passport.dwt');
    }
}

/* 密码找回-->输入用户名界面 */
elseif ($action == 'qpassword_name')
{
    //显示输入要找回密码的账号表单
    $smarty->display('user_passport.dwt');
}


/* 发送密码修改确认邮件 */
elseif ($action == 'send_pwd_email')
{
    include_once(ROOT_PATH . 'includes/lib_passport.php');

    /* 初始化会员用户名和邮件地址 */
    #$user_name = !empty($_POST['user_name']) ? trim($_POST['user_name']) : '';
    $email     = !empty($_POST['email'])     ? trim($_POST['email'])     : '';
	
    //用户名和邮件地址是否匹配
    $user_info = $user->get_user_info($email);
			
    if ($user_info && $user_info['email'] == $email)
    {
        //生成code
        //$code = md5($user_info[0] . $user_info[1]);

        $code = md5($user_info['user_id'] . $_CFG['hash_code'] . $user_info['reg_time']);
        //发送邮件的函数
        if (send_pwd_email($user_info['user_id'], $user_info['user_name'], $email, $code))
        {
            show_message($_LANG['send_success'] . $email, $_LANG['back_home_lnk'], './', 'info');
        }
        else
        {
            //发送邮件出错
            show_message($_LANG['fail_send_password'], $_LANG['back_page_up'], './', 'info');
        }
    }
    else
    {
        //用户名与邮件地址不匹配
        show_message($_LANG['no_email'], $_LANG['back_page_up'], './', 'info');
    }
}

/* 重置新密码 */
elseif ($action == 'reset_password')
{
    //显示重置密码的表单
    $smarty->display('user_passport.dwt');
}

/* 修改会员密码 */
elseif ($action == 'act_edit_password')
{
    include_once(ROOT_PATH . 'includes/lib_passport.php');

    $old_password = isset($_POST['old_password']) ? trim($_POST['old_password']) : null;
    $new_password = isset($_POST['new_password']) ? trim($_POST['new_password']) : '';
	$confirm_password = isset($_POST['confirm_password']) ? trim($_POST['confirm_password']) : '';
    $user_id      = isset($_POST['uid'])  ? intval($_POST['uid']) : $user_id;
	$user_name    = isset($_POST['user_name']) ? trim($_POST['user_name'])  : '';
	$email        = isset($_POST['email']) ? trim($_POST['email'])  : '';
	$email_daily        = isset($_POST['email_daily']) ? intval($_POST['email_daily'])  : 0;
	

    if (strlen($new_password) < 6 && !empty($new_password))
    {
        show_message($_LANG['passport_js']['password_shorter']);
    }
	
  	
	if($user->check_user($email))
	{
      	if ($user->edit_user(array('username'=> $user_name, 'password'=>$new_password, 'email'=>$email, 'user_id'=>$user_id, 'email_daily'=>$email_daily)))
      	{
	  
	      	$user->setUser($email);
			
			$GLOBALS['user']->set_session($email);
        	$GLOBALS['user']->set_cookie($email);
			
          	update_user_info();
		
			//判断数据库中的数据，对于已经award但是没有accept的project，判断accept时间期限，如果超过accept时间（awardDate），则清楚该proposal的award,将该project的status置为1，可继续投标、定标
			$fctime= date("Y-m-d H:i:s ",time());
			$sql = "SELECT * "." FROM " . $GLOBALS['ecs']->table('proposals'). " WHERE awarded=1 AND accepted=0 AND awardDate<'$fctime' ";
			$not_accept_ontime= $db->getALL($sql);
											
			foreach($not_accept_ontime as $each)
			{			
				$sql = "UPDATE " . $ecs->table('proposals') . " SET awarded=0 "." WHERE ppid='".$each[ppid]."'";
				$db->query($sql);
			
				$sql = "SELECT * FROM " . $ecs->table('projects') . " AS p JOIN ". $ecs->table('proposals') . " AS pp " . " WHERE pp.ppid='".$each[ppid]."' ";
				$tmp = $db->getRow($sql);
												
				$createdDate = strtotime($tmp['awardDate']);
						
				if($tmp['quoting'] == 1)
				{
					$tmpDate = $createdDate + 24*60*60*14;
					$endDate = date("Y-m-d H:i:s", $tmpDate); 				
				}
				else
				{
					$endDate = date("Y-m-d H:i:s", $createdDate + 24*60*60*30);
				}
				$createdDate = date("Y-m-d H:i:s", $createdDate);
					
				$sql = "UPDATE " . $ecs->table('projects') . " SET status=1, createdDate='$createdDate', endDate='$endDate' "." WHERE pid='".$each[pid]."'";
				$db->query($sql);
			}
		
        	show_message($_LANG['edit_password_success'], $_LANG['relogin_lnk'], 'user.php', 'info');
    		
      }
      else
      {
            show_message($_LANG['edit_password_failure'], $_LANG['back_page_up'], '', 'info');
      }
	}
	else
	{
		show_message("Password entered is incorrect, please enter it again", $_LANG['relogin_lnk'], 'user.php?act=profile', 'info');
	}
	
}


/**
 * 
 *
 * @param   integer $num
 * @param   integer $start
 *
 * @return  array
 */
function get_reviewed_list($num, $start, $user_id, $sort='id')
{
    /*   */	
	$sql = "SELECT * "." FROM " . $GLOBALS['ecs']->table('review')." AS r JOIN ". $GLOBALS['ecs']->table('users')." AS u "." WHERE r.reviewed_id = '".$user_id."' AND r.reviewer_id=u.user_id ";
	$sql = $sql." ORDER by ". $sort." DESC ";
	if($num != 0)
	{
		$sql = $sql." LIMIT ".$start.",".$num;
	}
	
	$reviewed = $GLOBALS['db']->getAll($sql);	
		
    return $reviewed;
}

/**
 * 
 *
 * @param   integer $num
 * @param   integer $start
 *
 * @return  array
 */
function get_reviewer_list($num, $start, $user_id, $sort='id')
{
    /*   */	
	$sql = "SELECT * "." FROM " . $GLOBALS['ecs']->table('review')." AS r JOIN ". $GLOBALS['ecs']->table('users')." AS u "." WHERE r.reviewer_id = '".$user_id."' AND r.reviewed_id=u.user_id ";
	$sql = $sql." ORDER by ". $sort." DESC ";
	if($num != 0)
	{
		$sql = $sql. " LIMIT ".$start.",".$num;
	}
	$reviewer = $GLOBALS['db']->getAll($sql);	
		
    return $reviewer;
}

?>